const {
  startTransaction,
  commitTransaction,
  rollbackTransaction,
} = require("./db.service");

module.exports = function transactionMiddleware() {
  return async (req, res, next) => {
    // 跳过非api请求
    if (!req.path.startsWith("/api")) {
      return next();
    }
    try {
      const connection = await startTransaction();
      req.db = {
        connection,
        commit: () => commitTransaction(connection),
        rollback: () => rollbackTransaction(connection),
      };
      const originalSend = res.send;
      res.send = function (body) {
        if (res.statusCode < 400) {
          return req.db
            .commit()
            .then(() => {
              originalSend.call(this, body);
            })
            .catch((err) => {
              console.error("事务提交失败:", err);
              originalSend.call(this, { code: 500, message: "事务提交失败" });
            });
        } else {
          return req.db
            .rollback()
            .then(() => {
              originalSend.call(this, body);
            })
            .catch((err) => {
              console.error("事务回滚失败:", err);
              originalSend.call(this, { code: 500, message: "事务回滚失败" });
            });
        }
      };
      next();
    } catch (error) {
      console.error("启动事务失败:", error);
      res.status(500).json({ code: 500, error: "启动事务失败" });
    }
  };
};
